package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Rotation;
import com.antdesignbackend.backend.service.RotationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

@RequestMapping("/rotation")
@Controller
public class RotationController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RotationService rotationService;

    @GetMapping("/index")
    @AuthToken
    public String index(){
        return "rotation/index";
    }

    /**
     * 分页查询首页轮播图
     * @param rotation
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody Rotation rotation) {
        ReturnVO returnVO = new ReturnVO();
        List<Rotation> datalist = new ArrayList<>();
        try {
            QueryWrapper<Rotation> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("type").orderByDesc("sort");
            if (rotation.getStatus() != -1){
                queryWrapper.eq("status",rotation.getStatus());
            }
            if (rotation.getType() != -1){
                queryWrapper.eq("type",rotation.getType());
            }
            int total = rotationService.count(queryWrapper);
            if (total > 0){
                datalist = rotationService.getBaseMapper().selectPage(new Page<Rotation>(rotation.getPageIndex(),rotation.getPageSize()),queryWrapper).getRecords();
                for (Rotation rotation1:datalist){
                    if (rotation1.getUrl() != null && !rotation1.getUrl().equals("")){
                        rotation1.setUrl(WebConfig.host+"images/"+rotation1.getUrl());
                    }
                }
            }
            returnVO.setTotal(total);
            returnVO.setData(datalist);
            return returnVO;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /***
     * 上传图片
     * @return
     */
    @PostMapping("/uploadImages")
    @ResponseBody
    public Map<String,String> uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8") ;
        long random =System.currentTimeMillis();
        String dateKey =random+"";
        String localPathDir="";
        String newFileName="";
        Map<String,String> map = new HashMap<>();
        if(!WebConfig.uploadImage.equals(""))
        {
            localPathDir=WebConfig.uploadImage;
        }
        else
        {
            localPathDir= ResourceUtils.getURL("classpath:").getPath()+"images/";
        }

        File logoSaveFile = new File(localPathDir);
        if(!logoSaveFile.exists()){
            logoSaveFile.mkdirs();
        }
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            Iterator iter = mr.getFileMap().values().iterator();
            if (iter.hasNext()) {
                MultipartFile file = (MultipartFile) iter.next();
                String oname = file.getOriginalFilename();
                String fileTyle=oname.substring(oname.lastIndexOf("."),oname.length());
                fileTyle=fileTyle.toLowerCase();
                newFileName=dateKey+fileTyle;
                String fileName = localPathDir+newFileName;
                if(fileTyle.equals(".png") || fileTyle.equals(".gif") || fileTyle.equals(".jpg"))
                {
                    File files = new File(fileName);
                    InputStream inputstream =file.getInputStream();
                    byte[] bytes = new byte[1024];
                    FileOutputStream outstream = new FileOutputStream(fileName);
                    int index;
                    while ((index = inputstream.read(bytes)) != -1) {
                        outstream.write(bytes, 0, index);
                        outstream.flush();
                    }
                    outstream.close();
                    inputstream.close();
                }
            }
        }
        if(newFileName!=null && !newFileName.equals(""))
        {
            map.put("url",newFileName);
            map.put("httpUrl",WebConfig.host+"images/"+newFileName);
        }
        return map;
    }

    /**
     * 保存
     * @param rotation
     * @return
     */
    @AuthToken
    @PostMapping("/save")
    @ResponseBody
    public ReturnVO save(@RequestBody Rotation rotation) {
        try {
            rotationService.saveOrUpdate(rotation);
            return new ReturnVO();
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 删除
     * @param rotationID
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public ReturnVO delCollection(@PathVariable("id") Integer rotationID){
        try {
            if(rotationID != null){
                rotationService.removeById(rotationID);
            }
            return new ReturnVO();
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 根据ID查询单条数据
     * @param rotationID
     * @return
     */
    @GetMapping("selectById")
    @ResponseBody
    public Rotation selectById(@RequestParam(value = "rotationID",required = false) Integer rotationID){
        Rotation rotation = new Rotation();
        try {
            if(rotationID != null){
                rotation = rotationService.getById(rotationID);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return rotation;
    }
}
